﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.PickCommand;
using ProductionManagement.Domain.Dtos;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;
using static Google.Protobuf.Reflection.UninterpretedOption.Types;

namespace ProductionManagement.Application.CommandHandler.PickCommandHandlers
{
    public class CreatePickCommandHandlers:IRequestHandler<CreatePickCommand,int>
    {
        private readonly IPickRepository _pick;

        private readonly IPickProductRepository _pickProduct;
        ISqlSugarClient db;
        IMapper _mapper;


        public CreatePickCommandHandlers(IPickRepository pick, IPickProductRepository pickProduct, ISqlSugarClient db, IMapper mapper)
        {
            _pick = pick;
            _pickProduct = pickProduct;
            this.db = db;
            _mapper = mapper;
        
        }

        public async Task<int> Handle(CreatePickCommand request, CancellationToken cancellationToken)
        {

            db.Ado.BeginTran();
            try
            {
                var pick = _mapper.Map<Picking>(request.AddPickDtos);
                var code = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                pick.PicNumber = $"SCLL{code}";
                await _pick.AddAsync(pick);


            

                foreach (var item in request.AddPickDtos.PickProdto)
                {
                    PickProduct pickProduct = new PickProduct()
                    {
                        PickProductId = item.PickProductId,
                        PickingId = pick.PicNumber,
                        ManpowerId = item.ManpowerId,
                        OutManager = item.OutManager,
                        OutshipState = item.OutshipState,
                        PickProductDelDate = item.PickProductDelDate,
                        PickProductNum = item.PickProductNum,
                        ProductId = item.ProductId,
                        AddName = item.AddName,
                        AddTime = item.AddTime,
                        User_Id = item.User_Id,
                        Office_Id = item.Office_Id,


                    };
                    await _pickProduct.AddAsync(pickProduct);
                }

                
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                //回滚
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
